﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Security.Cryptography;
using SalaDeEnsayo.ApplicationService.Model.Entity;
using SalaDeEnsayo.ApplicationService.Model;

namespace SalaDeEnsayo.ApplicationService
{
    public class MembershipService : BaseService
    {
        #region [ VARs ]

        UsuarioService usuarioS;
        RolService rolS;

        #endregion

        #region [ Constructor ]

        public MembershipService()
        {
            usuarioS = new UsuarioService();
            rolS = new RolService();
        }

        #endregion

        private string EncodePassword(string originalPassword)
        {
            SHA1 sha1 = new SHA1CryptoServiceProvider();

            byte[] inputBytes = (new UnicodeEncoding()).GetBytes(originalPassword);
            byte[] hash = sha1.ComputeHash(inputBytes);

            // Create a new Stringbuilder to collect the bytes
            // and create a string.
            StringBuilder sBuilder = new StringBuilder();

            // Loop through each byte of the hashed data 
            // and format each one as a hexadecimal string.
            for (int i = 0; i < hash.Length; i++)
            {
                sBuilder.Append(hash[i].ToString("x2"));
            }

            // Return the hexadecimal string.
            return sBuilder.ToString();
        }

        public bool ContraseniaValida(string nombreUsuario, string contrasena)
        {
            bool valido = false;
            using (IDataReader dr = this.SalaDeEnsayoDB.ExecuteReader("UsuarioLoginValido", nombreUsuario, EncodePassword(contrasena)))
            {
                if (dr.Read())
                {
                    valido = Convert.ToBoolean(dr["EsValido"]);
                }
            }
            return valido;
        }        

        public PrincipalInfo GetPrincipalInfo(string nombreUsuario)
        {
            Usuario usuario = usuarioS.GetUsuarioByUserName(nombreUsuario);
            var Roles = rolS.ListarRolesPorUsuario(usuario.Id);
            return new PrincipalInfo { UsuarioId = usuario.Id,
                                       roles = Roles.Select(r=> r.Nombre).ToList(),
                                       Activo = usuario.Activo};
        }
    }


    public class PrincipalInfo
    {
        public long UsuarioId { get; set; }
        public IList<string> roles { get; set; }
        public bool Activo { get; set; }
    }
}
